﻿namespace Client_Vkontakte
{

	using System.Windows.Forms;

	/// <summary>
	/// Helper login dialog for VK.
	/// </summary>
	/// <remarks>
	/// For more information about VK OAuth Dialog refer to
	/// http://vk.com/developers.php?id=-1_37230422&s=1
	/// and
	/// http://vk.com/developers.php?oid=-1&p=%D0%94%D0%B8%D0%B0%D0%BB%D0%BE%D0%B3_%D0%B0%D0%B2%D1%82%D0%BE%D1%80%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8_OAuth
	/// </remarks>
	public partial class VKLoginDialog : Form
	{

		#region Fields

		private readonly System.Uri _loginUrl = null;
		private VK.Lib.VKOAuthResult _vkOAuthResult = null;

		#endregion

		public VK.Lib.VKOAuthResult VKOAuthResult
		{
			get
			{
				return this._vkOAuthResult;
			}
			private set
			{
				this._vkOAuthResult = value;
			}
		}

		public VKLoginDialog(string appId, string scope)
		{
			if (System.String.IsNullOrEmpty(appId))
				throw new System.ArgumentNullException("appId");

			// Make sure to set the app id.
			var oauthClient = new VK.Lib.VKOAuthClient { AppId = appId, Scope = scope };

			System.Collections.Generic.IDictionary<string, object> loginParameters = new System.Collections.Generic.Dictionary<string, object>();

			// list of additional display modes can be found at http://vk.com/developers.php?oid=-1&p=%D0%94%D0%B8%D0%B0%D0%BB%D0%BE%D0%B3_%D0%B0%D0%B2%D1%82%D0%BE%D1%80%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8_OAuth
			loginParameters["display"] = "page";

			// when the Form is loaded navigate to the login url.
			this._loginUrl = oauthClient.GetLoginDialogUrl(loginParameters);

			InitializeComponent();
		}

		private void LoginDialog_FormClosing(object sender, FormClosingEventArgs e)
		{
			System.GC.Collect(1, System.GCCollectionMode.Forced);
			System.GC.WaitForPendingFinalizers();
		}

		private void VKLoginDialog_Load(object sender, System.EventArgs e)
		{
			// make sure to use the AbsoluteUri.
			webBrowser.Navigate(this._loginUrl.AbsoluteUri);
		}

		private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
		{
			// whenever the browser navigates to a new url, try parsing the url
			// the url may be the result of OAuth 2.0 authentication.

			VK.Lib.VKOAuthResult oauthResult = null;

			// If try parse, the url is the result of OAuth 2.0 authentication,
			//else the url is NOT the result of OAuth 2.0 authentication.
			if (VK.Lib.VKOAuthResult.TryParse(e.Url, out oauthResult))
			{
				this.VKOAuthResult = oauthResult;
				this.DialogResult = this.VKOAuthResult.IsSuccess ? DialogResult.OK : DialogResult.No;
			}
			else
				this.VKOAuthResult = null;
		}

	}

}